package com.zaoke.web.dao.user.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.jdbc.core.RowMapper;

import com.zaoke.web.bo.query.user.UserQuery;
import com.zaoke.web.bo.user.User;
import com.zaoke.web.dao.JdbcSupport;
import com.zaoke.web.dao.user.UserDao;

public class UserDaoImpl extends JdbcSupport implements UserDao{

//	private static final long DAY = 24*60*60*1000;
//	
//	private static final long EIGHT = 8*60*60*1000;
	
	private static final String TABLE = "`zaoke`.`user`";
	private static final String QUERY_VIEW = "`user_id`, `card_id`, `user_name`, `cell_phone`, `zone_id`, `balance`, `state`, `register_time`, `last_buy_time`, `mod_time`, `consume`, `password`";

	public User getUserInfo(long userid){
		String sql = "select " + QUERY_VIEW + " from " + TABLE + " where `user_id` order by mod_time desc limit 1";
		
		List<User> users = getTemplateMgr().getReadTp().query(sql,new RowMapper<User>() {
			public User mapRow(ResultSet rs, int rowNum) throws SQLException {
				User user = new User();
				user.setUserId(rs.getLong("user_id"));
				user.setCardId(rs.getLong("card_id"));
				user.setUserName(rs.getString("user_name"));
				user.setCellPhone(rs.getLong("cell_phone"));
				user.setZoneId(rs.getLong("zone_id"));
				user.setBalance(rs.getDouble("balance"));
				user.setState(rs.getInt("state"));
				user.setRegisterTime(rs.getDate("register_time"));
				user.setLastBuyTime(rs.getDate("last_buy_time"));
				user.setModTime(rs.getDate("mod_time"));
				user.setConsume(rs.getDouble("consume"));
				user.setPassword(rs.getString("password"));
				return user;
			}
		},userid);
		
		if(users != null && users.size() > 0)
			return users.get(0);
		else
			return null;
	}
	public long addAutoUser(final User user) {
		final String sql = "insert into " + TABLE + " (`user_name`, `state`, `register_time`, `mod_time`) values(?, ?, ?,?)";
		int count = getTemplateMgr().getWriteTp().update(sql, user.getUserName(),user.getState(),user.getRegisterTime(),user.getModTime());
		
		return count;
	}
	
	public List<User> queryUserInfo(UserQuery query)
	{
		List<User> res = new ArrayList<User>();
		
		if(query!=null)
		{
			String sql = "select " + QUERY_VIEW + " from " + TABLE + " where 1=1 ";
			List<Object> params = new LinkedList<Object>();
			Long userid = query.getUserid();
			
			if(userid!=null)
			{
				sql += " and user_id=? ";
				params.add(userid);
				
			}
			Long cardid = query.getCardid();
			if(cardid!=null)
			{
				sql += " and card_id=? ";
				params.add(cardid);
			}
			String cellphone = query.getCellphone();
			if(cellphone!=null && !"".equals(cellphone))
			{
				sql += " and cell_phone=? ";
				params.add(cellphone);
			}
			Integer zoneid = query.getZoneid();
			if(zoneid!=null && zoneid!=-1)
			{
				sql += " and zone_id=? ";
				params.add(zoneid);
			}
//			Date register = query.getRegister();
			if(query.getRegisterF() != null && query.getRegisterT() != null)
			{
//				register = new Date(register.getTime()-EIGHT);
//				Date nextDay = new Date(register.getTime()+DAY);
				sql += " and register_time between ? and ? ";
				params.add(DateUtils.truncate(query.getRegisterF(), Calendar.DATE));
				params.add(DateUtils.ceiling(query.getRegisterT(), Calendar.DATE));
			}
//			Date lastbuy = query.getLastbuy();
			if(query.getLastbuyF() != null && query.getLastbuyT() != null)
			{
//				lastbuy = new Date(lastbuy.getTime()-EIGHT);
//				Date nextDay = new Date(lastbuy.getTime()+DAY);
				sql += " and last_buy_time between ? and ? ";
				params.add(DateUtils.truncate(query.getLastbuyF(), Calendar.DATE));
				params.add(DateUtils.ceiling(query.getLastbuyT(), Calendar.DATE));
			}
			Double balancestart = query.getBalancestart();
			if(balancestart!=null)
			{
				sql += " and balance>=? ";
				params.add(balancestart);
			}
			Double balanceend = query.getBalanceend();
			if(balanceend!=null)
			{
				sql += " and balance<=? ";
				params.add(balanceend);
			}
			Double consumestart = query.getConsumestart();
			if(consumestart!=null)
			{
				sql += " and consume>=? ";
				params.add(consumestart);
			}
			Double consumeend = query.getConsumeend();
			if(consumeend!=null)
			{
				sql += " and consume<=? ";
				params.add(consumeend);
			}
			Integer state = query.getState();
			if(state!=null && state >= 0)
			{
				/*if(state==User.STATE_AUTO)
				{
					sql += " and state in (0,2) ";
				}
				else
				{
					sql += " and state=1 ";
				}*/
				sql += " and state= " + state;
					
			}
			res = getTemplateMgr().getReadTp().query(sql, new RowMapper<User>() {
				public User mapRow(ResultSet rs, int rowNum) throws SQLException {
					User user = new User();
					user.setUserId(rs.getLong("user_id"));
					user.setCardId(rs.getLong("card_id"));
					user.setUserName(rs.getString("user_name"));
					user.setCellPhone(rs.getLong("cell_phone"));
					user.setZoneId(rs.getLong("zone_id"));
					user.setBalance(rs.getDouble("balance"));
					user.setState(rs.getInt("state"));
					user.setRegisterTime(rs.getDate("register_time"));
					user.setLastBuyTime(rs.getDate("last_buy_time"));
					user.setModTime(rs.getDate("mod_time"));
					user.setConsume(rs.getDouble("consume"));
					user.setPassword(rs.getString("password"));
					user.setStateDesc(transState(rs.getInt("state")));
					return user;
				}
				private String transState(int state)
				{
					switch(state)
					{
					case 0:
						return "自动生成";
					case 1:
						return "锁定";
					case 2:
						return "用戶注册";
					}
					return "";
				}
			}, params.toArray());
		}
		
		return res;
	}
	
	@Override
	public Map<Long, User> getUserInfos(Set<Long> userIds) {
		String sql = "select " + QUERY_VIEW + " from " + TABLE + " where user_id in (";
		sql += StringUtils.join(userIds, ",");
		sql += ")";
		
		final Map<Long, User> users = new HashMap<Long, User>();	
		
		getTemplateMgr().getReadTp().query(sql, new RowMapper<User>() {
			public User mapRow(ResultSet rs, int rowNum) throws SQLException {
				User user = new User();
				user.setUserId(rs.getLong("user_id"));
				user.setCardId(rs.getLong("card_id"));
				user.setUserName(rs.getString("user_name"));
				user.setCellPhone(rs.getLong("cell_phone"));
				user.setZoneId(rs.getLong("zone_id"));
				user.setBalance(rs.getDouble("balance"));
				user.setState(rs.getInt("state"));
				user.setRegisterTime(rs.getDate("register_time"));
				user.setLastBuyTime(rs.getDate("last_buy_time"));
				user.setModTime(rs.getDate("mod_time"));
				user.setConsume(rs.getDouble("consume"));
				user.setPassword(rs.getString("password"));
				users.put(user.getUserId(), user);
				return user;
			}
		});
		
		return users;
	}
}
